<template>
    <!-- 信用量管理 -->
    <div>
        <section class="business-wrapper">
            <el-form
                ref="form"
                :model="queryForm"
                label-width="80px"
                :inline="true"
                class="queryForm"
            >
				<!--S 预警类型-->
                <el-row class="business-status">
                    <el-form-item label="预警类型:" class="mb13">
                        <el-radio-group v-model="queryForm.warnType">
                        	<el-radio-button label="0" key="0">全部</el-radio-button>
                            <el-radio-button :label="item.value" :key="item.value"
                                             v-for="item in  selectData">
                                {{ item.label }}
                            </el-radio-button>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="仅看询问:" class="ml60 mb13">
                        <el-radio-group v-model="queryForm.checkInquiry">
                        	<el-radio label="0" key="0">是</el-radio>
                        	<el-radio label="1" key="1">否</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-row>
				<!--E 预警类型-->
				<!--E 预警时间-->
				<el-row class="more-content">
                    <el-form-item label="预警时间:" class="mb13">
                        <el-radio-group v-model="ckecked" @change="changeTime">
                            <el-radio-button label="1">今日</el-radio-button>
                            <el-radio-button label="2">本周</el-radio-button>
                            <el-radio-button label="3">本月</el-radio-button>
                            <el-radio-button label="4">上月</el-radio-button>
                            <el-radio-button label="5">本年</el-radio-button>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="自定义" class="customized mb13">
                        <el-date-picker
                            v-model="queryForm.dateTime"
                            type="daterange"
                            :picker-options="pickerOptions"
                            range-separator="至"
                            value-format="yyyy-MM-dd"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            align="center">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item class="mb13">
	                    <div class="but-container ml50">
                            <el-button
                                type="primary"
                                class="search-btn"
                                size="small"
                                style="margin-right:5px"
                                @click="
            getList(
              page,
              orderBy.name,
              orderBy.method,
              queryForm.dateTime,
              0,
              queryForm.warnType,
              queryForm.companyName,
              queryForm.productId,
              queryForm.dataType,
              queryForm.keyWord,
              queryForm.checkInquiry
            )">查询
                            </el-button>
                            <el-button size="small" @click="reset">重置</el-button>
                        	
			                <!--<div class="more" @click="showMore=!showMore">更多筛选条件<i class="el-icon-arrow-down"></i></div>-->

                        </div>
                    </el-form-item>
                </el-row>
				<!--E 预警时间-->



                <el-row class="more-content company-name">
                </el-row>
                <el-row class="btn-content">

                </el-row>
            </el-form>
        </section>
        <div class="btn-wrapper mt7">
            <el-button size="small" v-if="hasPermission('warn:info:del')"
                       @click="del">删除
            </el-button>
            <section class="right-but" style="display:flex;margin-right: 0">
				<el-button type="text" style="margin-right:-13px" @click="refreshList(page,orderBy.name,orderBy.method)">
					<img style="width:44px;height:36px;" src="~@/assets/img/shuaxin.png">
				</el-button>
				<PopoverBut class="selectBut" ref="popoverBut" :checkedProps="checkedProps" :options="options" @getCheckeds="handlerCloumn"></PopoverBut>
			</section>
        </div>
        <el-table
            size="mini"
            v-loading="loading"
            :data="tableData"
            style="width: 100%; margin-top: 10px"
            border
            :header-cell-style="{
        'background-color': '#eeeeee !important',
      }"
            :row-class-name="tableRowClassName"
            @selection-change="tableSelected"
            @sort-change="sortthiscolumn">
            <el-table-column
                type="selection"
                width="60">
            </el-table-column>
            <el-table-column type="index" label="序号" width="70" align="center">
                <template slot-scope="scope">
          <span>{{
                  (page.pageNo - 1) * page.pageSize + scope.$index + 1
              }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="warnDescribe" label="内容">
                <template slot-scope="scope">
                    <span v-if="scope.row.dealType===1">
                        <el-link @click="prompt(scope.row)" target="_blank">询问：{{scope.row.warnDescribe}}</el-link>
                    </span>
                    <span v-else-if="scope.row.dealType===2">
                        <el-link @click="prompt(scope.row)" target="_blank">提示：{{scope.row.warnDescribe}}</el-link>
                    </span>
                </template>
            </el-table-column>

            <el-table-column prop="warnType" label="预警类型">
                <template slot-scope="scope">
                    {{$dictUtils.getDictLabel("warnType", scope.row.warnType, "")}}
                </template>
            </el-table-column>
            <el-table-column prop="warnTimeFlag" label="发生时间"></el-table-column>
        </el-table>
        <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :page-size="page.pageSize"
            :current-page="page.pageNo"
            layout="total,sizes,prev, pager, next, jumper"
            :total="page.total"
        >
        </el-pagination>

        <WarnInfoForm
            ref="WarnInfoForm"
            @refreshDataList="getList(page,orderBy.name,orderBy.method,null,state)"
        ></WarnInfoForm>
    </div>
</template>
<script>
    import {getSelectList,getList, del, updateState} from '@/api/warnInfo/WarnInfo.js';
    import PopoverBut from '@/components/button/popoverBut'
    import WarnInfoForm from './warnInfoForm'


    const options1 = []
    const cityOptions = ['上海', '北京']
    export default {
        components: {
            PopoverBut, WarnInfoForm
        },
        data() {
            return {
            	showMore:false,
                state: 0, // 状态（0:未处理；1:已处理；）
                ids: [], // 选中的数据id数组
                status: [], // 选中的数据状态数组
                dealTypes: [], // 选中的数据处理类型数组
                processTypeData: [],
                selectData: [],
                ckecked: '1',
                queryForm: {
                    keyWord: '',
                    modelId: '',
                    dateTime: '',
                    state: '',
                    getMoneyType: '',
                    dataType: '',
                    contractCode: '',
                    companyId: '',
                    companyName: '',
                    productId: '',
                    productName: '',
                    checkedState: '1',
                    name: '',
                    warnType:'0',
                    checkInquiry:"0"
                },
                pickerOptions: { // 时间选项
                    shortcuts: [{
                        text: '近7日',
                        onClick(picker) {
                            const end = new Date()
                            const start = new Date()
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
                            picker.$emit('pick', [start, end])
                        }
                    }, {
                        text: '近15日',
                        onClick(picker) {
                            const end = new Date()
                            const start = new Date()
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 15)
                            picker.$emit('pick', [start, end])
                        }
                    }, {
                        text: '近30日',
                        onClick(picker) {
                            const end = new Date()
                            const start = new Date()
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
                            picker.$emit('pick', [start, end])
                        }
                    }]
                },
                value2: '',
                checkedProps: options1,
                ShowCloum: {createDate: ''},
                options: [
                    {label: '上次操作时间', key: '2'},
                    {label: '创建时间', key: 'createDate'}
                ],
                tableData: [],
                orderBy: {
                    name: 'create_date',
                    method: 'desc'
                },
                loading: false,
                page: {
                    pageSize: 10,
                    pageNo: 1,
                    total: 0
                },
                props: 1,
                checkedCities: [],
                cities: cityOptions
            }
        },
        methods: {

            // 提示弹窗
            prompt(row) {
                if (row.state === 0) {
                    this.$refs.WarnInfoForm.init('info', row);
                }
            },
            // 多选
            tableSelected(val) {
                // 去重获取被选中的id值存入到数组中
                this.ids = []
                this.modelIds = []
                for (let selectedItem of val) {
                    this.ids.push(selectedItem.id)
                }
                console.log(this.ids);
            },
            // 获取磅单模版下拉列表数据
            getSelectList (state) {
                getSelectList({state: state
                }).then((res) => {
                    if (res.data.code === '200') {
                        this.selectData = res.data.result
                        
//                      this.selectData = [
//                      	{label:'业务余量不足',value:1},
//                      	{label:'皮重异常',value:2},
//                      	{label:'毛重异常',value:3},
//                      ]
                    }
                })
            },
            // 导出
            exportExcel(processType, params, orderName, orderByAORC, queryDateTime, queryState, getMoneyType, companyName, productId, modelId, dataType, keyWord) {
                this.$http({
                    method: 'get',
                    url: '/business/export',
                    params: {
                        processType: processType,
                        pageSize: params.pageSize,
                        pageNo: params.pageNo,
                        orderBy: orderName,
                        orderByAORC: orderByAORC,
                        contractStartDate: queryDateTime == null ? null : queryDateTime[0],
                        contractEndDate: queryDateTime == null ? null : queryDateTime[1],
                        state: queryState,
                        getMoneyType: getMoneyType,
                        companyName: companyName,
                        productId: productId,
                        modelId: modelId,
                        dataType: dataType,
                        keyWord: keyWord
                    },
                    responseType: 'blob'
                }).then(response => {
                    if (!response) {
                        return
                    }
                    let link = document.createElement('a')
                    link.href = window.URL.createObjectURL(new Blob([response.data]))
                    link.target = '_blank'
                    let filename = response.headers['content-disposition']
                    link.download = decodeURI(filename)
                    document.body.appendChild(link)
                    link.click()
                    document.body.removeChild(link)
                    // eslint-disable-next-line handle-callback-err
                }).catch((error) => {

                })
            },
            // 改变状态
            editState(state, row) {
                this.$confirm('是否修改状态?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then((res) => {
                    updateState({id: row.id, state: state}).then(res => {
                        if (res.data.code === '200') {
                            this.$message({
                                type: 'success',
                                message: '状态修改成功'
                            })
                            this.getList(this.page, this.orderBy.name, this.orderBy.method,null, this.state)
                        }
                    })
                })
            },
            // 删除业务
            del() {
                if (this.ids.length == 1) {
                    var str = ''
                    for (var i = 0; i < this.ids.length; i++) {
                        str += this.ids[i] + ','
                    }
                    // 去掉最后一个逗号(如果不需要去掉，就不用写)
                    if (str.length > 0) {
                        str = str.substr(0, str.length - 1)
                    }
                    this.loading = true
                    del({
                        ids: str
                    }).then((res) => {
                        if (res.data.code === '200') {
                            this.getList(this.page, this.orderBy.name, this.orderBy.method, null, this.state);
                            this.$message({
                                type: 'success',
                                message: '删除成功'
                            })
                        } else {
                            this.$message({
                                type: 'error',
                                message: res.data.message
                            })
                        }
                        this.loading = false
                    })
                } else {
                    this.$notify.error({
                        title: '错误',
                        message: '请选择单条数据'
                    })
                }
            },
            goToAddForm() {
                this.$router.push({path: './addBusinessView'})
            },

            changeTime(value) {
                this.ckecked = value
                if (value === '1') {
                    const start = new Date(new Date(new Date().toLocaleDateString()).getTime())
                    const end = new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1)
                    this.queryForm.dateTime = [start, end]
                }
                if (value === '2') {
                    const start = getMonday('s', 0)
                    const end = getMonday('e', 0)
                    const newStart = start + ' 00:00:00'
                    const newEnd = end + ' 23:59:59'
                    this.queryForm.dateTime = [newStart, newEnd]
                }
                if (value === '3') {
                    const start = getMonth('s', 0)
                    const end = getMonth('e', 0)
                    const newStart = start + ' 00:00:00'
                    const newEnd = end + ' 23:59:59'
                    this.queryForm.dateTime = [newStart, newEnd]
                }
                if (value === '4') {
                    const start = getMonth('s', -1)
                    const end = getMonth('e', -1)
                    const newStart = start + ' 00:00:00'
                    const newEnd = end + ' 23:59:59'
                    this.queryForm.dateTime = [newStart, newEnd]
                }
                if (value === '5') {
                    const start = getYear('s', 0)
                    const end = getYear('e', 0)
                    const newStart = start + ' 00:00:00'
                    const newEnd = end + ' 23:59:59'
                    this.queryForm.dateTime = [newStart, newEnd]
                }
            },
            // 获取列表带分页
            getList(params, orderName, orderByAORC, queryDateTime, queryState, queryWarnType, companyName, productId, dataType, keyWord,checkInquiry) {
                this.loading = true
                getList({
                    pageSize: params.pageSize,
                    pageNo: params.pageNo,
                    orderBy: orderName,
                    orderByAORC: orderByAORC,
                    contractStartDate: queryDateTime == null ? null : queryDateTime[0],
                    contractEndDate: queryDateTime == null ? null : queryDateTime[1],
                    state: queryState,
                    warnType: queryWarnType,
                    companyName: companyName,
                    productId: productId,
                    dataType: dataType,
                    keyWord: keyWord
                }).then((res) => {
                    if (res.data.code === '200') {
                        this.tableData = res.data.result.list
                        this.page.total = res.data.result.count
                    }
                    this.loading = false
                })
            },
            reset() {
                this.queryForm.modelId = '',
                this.queryForm.dateTime = '',
                this.queryForm.warnType = '0',
                this.queryForm.getMoneyType = '',
                this.queryForm.dataType = '',
                this.queryForm.contractCode = '',
                this.queryForm.companyId = '',
                this.queryForm.companyName = '',
                this.queryForm.productId = '',
                this.queryForm.productName = '',
                this.queryForm.checkedState = '',
                this.queryForm.name = '',
                this.queryForm.checkInquiry = '0'
            },
            // 排序
            sortthiscolumn(a) {
                this.orderBy.name = a.prop
                this.page.pageNo = 1
                if (a.order === 'ascending') {
                    this.orderBy.method = 'asc'
                } else {
                    this.orderBy.method = 'desc'
                }
                this.getList(this.page, this.orderBy.name, this.orderBy.method,null, this.state)
            },
            handleSizeChange(e) {
                this.page.pageSize = e
                this.getList(this.page, this.orderBy.name, this.orderBy.method,null, this.state)
            },
            handleCurrentChange(e) {
                this.page.pageNo = e
                this.getList(this.page, this.orderBy.name, this.orderBy.method,null, this.state)
                console.log(e)
            },
            tableRowClassName({row, rowIndex}) {
                if (rowIndex % 2 === 1) {
                    return 'warning-row'
                } else {
                    return 'success-row'
                }
            },

        },
        mounted() {
            this.getList(this.page, this.orderBy.name, this.orderBy.method, null, this.state);
            this.getSelectList(this.state);
        }
    }
    // 得到本周、上周、下周的起始、结束日期
    // getMonday(type,dates)  //type为字符串类型，有两种选择，"s"代表开始,"e"代表结束，dates为数字类型，不传或0代表本周，-1代表上周，1代表下周
    // getMonday("s",1)  //得到下周一的yyyy-mm-dd格式日期
    // getMonday("e",1)  //得到下周日的yyyy-mm-dd格式日期
    function getMonday(type, dates) {
        var now = new Date()
        var nowTime = now.getTime()
        var day = now.getDay()
        var longTime = 24 * 60 * 60 * 1000
        var n = longTime * 7 * (dates || 0)
        if (type == 's') {
            var dd = nowTime - (day - 1) * longTime + n
        }
        ;
        if (type == 'e') {
            var dd = nowTime + (7 - day) * longTime + n
        }
        ;
        dd = new Date(dd)
        var y = dd.getFullYear()
        var m = dd.getMonth() + 1
        var d = dd.getDate()
        m = m < 10 ? '0' + m : m
        d = d < 10 ? '0' + d : d
        var day = y + '-' + m + '-' + d
        return day
    };
    // 得到本月、上月、下月的起始、结束日期
    // getMonth(type,months)  //type为字符串类型，有两种选择，"s"代表开始,"e"代表结束，months为数字类型，不传或0代表本月，-1代表上月，1代表下月
    // getMonth("s",1)  //得到下月第一天的yyyy-mm-dd格式日期
    // getMonth("e",1)  //得到下月最后一天的yyyy-mm-dd格式日期
    function getMonth(type, months) {
        var d = new Date()
        var year = d.getFullYear()
        var month = d.getMonth() + 1
        if (Math.abs(months) > 12) {
            months = months % 12
        }
        ;
        if (months != 0) {
            if (month + months > 12) {
                year++
                month = (month + months) % 12
            } else if (month + months < 1) {
                year--
                month = 12 + month + months
            } else {
                month = month + months
            }
            ;
        }
        ;
        month = month < 10 ? '0' + month : month
        var date = d.getDate()
        var firstday = year + '-' + month + '-' + '01'
        var lastday = ''
        if (month == '01' || month == '03' || month == '05' || month == '07' || month == '08' || month == '10' || month == '12') {
            lastday = year + '-' + month + '-' + 31
        } else if (month == '02') {
            if ((year % 4 == 0 && year % 100 != 0) || (year % 100 == 0 && year % 400 == 0)) {
                lastday = year + '-' + month + '-' + 29
            } else {
                lastday = year + '-' + month + '-' + 28
            }
            ;
        } else {
            lastday = year + '-' + month + '-' + 30
        }
        ;
        var day = ''
        if (type == 's') {
            day = firstday
        } else {
            day = lastday
        }
        ;
        return day
    };

    // 得到今年、去年、明年的开始、结束日期
    // getYear(type,dates)  //type为字符串类型，有两种选择，"s"代表开始,"e"代表结束，dates为数字类型，不传或0代表今年，-1代表去年，1代表明年
    // getYear("s",1)  //得到明年第一天的yyyy-mm-dd格式日期
    // getYear("e",1)  //得到明年最后一天的yyyy-mm-dd格式日期
    function getYear(type, dates) {
        var dd = new Date()
        var n = dates || 0
        var year = dd.getFullYear() + Number(n)
        if (type == 's') {
            var day = year + '-01-01'
        }
        ;
        if (type == 'e') {
            var day = year + '-12-31'
        }
        ;
        if (!type) {
            var day = year + '-01-01/' + year + '-12-31'
        }
        ;
        return day
    };
</script>
<style lang="scss" scoped>
@import '@/assets/scss/config.scss';
.mb13{
	margin-bottom: 13px !important;
}
.ml50{
	margin-left: 50px;
}
.mt20{
	margin-top: 20px;
}
.ml60{
	margin-left: 60px !important;
}
.mt7{
	margin-top: 7px;
}
.right-but{
	margin-top: 0 !important;
}
.customized{
	::v-deep.el-input__icon{
		/*opacity: 0;*/
	}
	::v-deep.el-range-editor.el-input__inner{
		width: 280px;
	}
	::v-deep.el-date-editor .el-range-separator{
		width: 30px !important;
	}
}
    .business-wrapper {
		
        ::v-deep.el-form {

			.el-radio__label{
				font-size: 16px;
				padding-left: 8px;
			}
            .el-row {

                .el-form-item {
                    margin: 0;
                    .el-radio-button__inner:hover {
							color: $--color-primary-liyu;
			          		border-color: $--color-primary-liyu;
                    }
					.el-radio-button.is-active{
						.el-radio-button__inner,{
							color: $--color-primary-liyu;
			          		border-color: $--color-primary-liyu;
							
						}
					}
                }

                .el-radio-button__inner {
                    background: #FFFFFF;
                    border-radius: 4px;
                    font-size: 16px;
                    font-family: Microsoft YaHei;
                    font-weight: 400;
                    padding: 6px 9px;
                    border: 1px solid transparent;
                    color: #333333;
                    margin-right: 10px;
                    vertical-align: middle;
                }

                .el-radio-button__orig-radio:checked + .el-radio-button__inner, .el-radio-button__inner:hover {
                    border: 1px solid #1890FF;
                    color: #1890FF;
                    box-shadow: none;
                }
            }

            .el-row.btn-content {

                .but-container {

                    .more-button {
                        display: inline-block;
                        margin-left: 47px;
                        font-size: 12px;
                        font-family: Microsoft YaHei;
                        font-weight: 400;
                        color: #666666;
                        cursor: pointer;
                        vertical-align: top;
                    }

                }
            }

            .el-row.getMoney-type {

                .el-form-item:first-child {
                    margin-right: 197px;
                }

            }

            .el-row.company-name {

                .el-form-item:first-child {
                    margin-right: 30px;
                }

                .el-form-item__label {
                    line-height: 36px;
                }

            }
        }

        ::v-deep.el-form.more {

            .el-row.business-status {

                .el-input__inner {
                    width: 350px;
                }

            }

            .el-row:first-child, .el-row.business-status, .el-row.getMoney-type {
                margin-bottom: 13px;
            }

            .el-row:nth-child(2) {
                margin-bottom: 20px;
            }

            .el-row.company-name, .el-row.btn-content {
                margin-bottom: 20px;
            }

            .more-content {
                display: block;
            }

            .el-row.btn-content {
                padding-left: 460px;
            }

            .el-input.el-input-group {

                input {
                    width: 312px;
                }

            }
        }

        ::v-deep.el-form.less {

            .el-row {
                margin-bottom: 13px;
            }

            .btn-content {
                position: absolute;
                bottom: 0;
                left: 784px;
                margin-bottom: 0;

                .el-form-item {
                    margin-bottom: 0;
                }

            }

            .business-status {
                margin-bottom: 20px;

                .el-form-item {
                    margin-bottom: 0;

                    .el-input__inner {
                        width: 350px;
                    }

                }
            }
        }
    }

    .btn-wrapper {

        .btn-set {
            width: 85px;
        }

    }

    ::v-deep.el-table {

        th:nth-child(2) .cell, td:nth-child(2) .cell {
            padding: 0 !important;
        }

        .cell {

            p {
                margin: 0 0 8px;
            }

            .mark {
                display: inline-block;
                width: 20px;
                height: 20px;
                border-radius: 4px;
                line-height: 18px;
                text-align: center;
                font-size: 12px;
                margin-right: 11px;
                vertical-align: bottom;
            }

            .mark.total {
                border: 1px solid #666666;
                color: #666666;
            }

            .mark.surplus {
                border: 1px solid #F59A23;
                color: #F59A23;
            }

        }
    }

    .queryForm {
        position: relative;
    }

    .right-but {
        float: right;
        margin-right: 10px;
        margin-top: -20px;
    }
</style>
